<template>
  <div class="center_box">
    <h3 style="text-align: center">个人中心</h3>
    <div>当前用户:{{this.$store.state.user.username}} <a href="javascript:;" @touchstart="handleToLogout">退出</a></div>
    <div v-if="$store.state.user.isAdmin">用户身份：管理员<a href="/admin" target="_blank">进入管理员页面</a></div>
    <div v-else >用户身份：普通会员</div>
    <div style="margin-top:10px;">
      <img style="width:100px;height:100px;border-radius:50%" :src="$store.state.user.avatar" alt="">
      头像上传：<input type="file" name="file" @change="handleToUpload">
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import {messageBox} from '@/components/js'
export default {
  methods: {
    async handleToLogout() {
      let res = await this.$axios.get('/api2/users/logout')
      if(res.data.status === 0) {
        localStorage.removeItem('username')
        localStorage.removeItem('isAdmin')
        localStorage.removeItem('avatar')
        this.$store.commit('user/USER_NAME', {username: '', isAdmin: false, avatar:''})
        this.$router.push('/mine/login')
      }
    },
    async handleToUpload(e) {
      let file = e.target.files[0]
      let param = new FormData()
      param.append('file', file, file.name)
      let config = {
        headers: {
          'Content-Types': 'multipart/form-data'
        }
      }
      let res = await this.$axios.post('/api2/users/uploadAvatar', param, config)
      let that = this
      if(res && res.data.status === 0) {
        messageBox({
          title: '信息',
          content: res.data.msg,
          ok: '确定',
          handleOk() {
            that.$store.commit('user/USER_NAME', {
              avatar: res.data.data.avatar + '?' + Math.random(),
              username: that.$store.state.user.username,
              isAdmin: JSON.parse(window.localStorage.isAdmin),
            })
            localStorage.setItem('avatar', res.data.data.avatar)
          }
        })
      }else {
        mesageBox({
          title: '信息',
          content: res.data.msg,
          ok: '确定'
        })
      }
    }
  },
  async beforeRouteEnter(to, from, next) {
    let res = await axios.get('/api2/users/getUser')
    if(res.data.status === 0) {
      next(vm=> {
        vm.$store.commit('user/USER_NAME', {
          username: res.data.data.username,
          isAdmin: res.data.data.isAdmin,
          avatar: res.data.data.avatar,
        })
        localStorage.setItem('username', res.data.data.username)
        localStorage.setItem('isAdmin',JSON.stringify(res.data.data.isAdmin))
        localStorage.setItem('avatar', res.data.data.avatar)
      })
    }else {
      next('/mine/login')
    }
  }
}
</script>

<style scoped>
.center_box {
  background-color: #f8f8f8;
  padding: 10px;
  text-align: center
}
</style>
